/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PlayListPanel.java
 *
 * Created on Jun 30, 2009, 4:14:03 PM
 */

package coda.gui;

import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import org.bff.javampd.MPD;
import org.bff.javampd.MPDDatabase;
import org.bff.javampd.objects.MPDAlbum;
import org.bff.javampd.objects.MPDArtist;
import org.bff.javampd.objects.MPDSong;

enum Icon {
    ARTIST("artist.png"),
    ALBUM("album.png"),
    SONG("song.png");

    private final ImageIcon icon;

    Icon(String name) {
        this.icon = new ImageIcon(getClass().getResource("/resources/" + name));
    }
    public ImageIcon image() {return icon;}
}

/**
 *
 * @author pan
 */
public class CollectionPanel extends javax.swing.JPanel {

    private MPD mpd;
    private DefaultTreeModel model;

    /** Creates new form PlayListPanel */
    public CollectionPanel(MPD mpd) {
        initComponents();
        //
        this.mpd = mpd;
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("All");
        model = new DefaultTreeModel(root){
            @Override
            public boolean isLeaf(Object node) {
                Object obj = ((DefaultMutableTreeNode) node).getUserObject();
                return obj instanceof MPDSong;
            }
        };
        tree.setModel(model);
        //
        tree.setCellRenderer(new DefaultTreeCellRenderer(){
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, false);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object obj = node.getUserObject();
                if (obj instanceof MPDSong) {
                    MPDSong s = (MPDSong) node.getUserObject();
                    setText(s.getTitle());
                    setIcon(Icon.SONG.image());
                } else if (obj instanceof MPDArtist) {
                    setIcon(Icon.ARTIST.image());
                } else if (obj instanceof MPDAlbum) {
                    setIcon(Icon.ALBUM.image());
                }
                return this;
            }
        });
        //
        listArtists(root);
    }

    public void refresh() {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        listArtists(root);
    }

    private void listArtists(DefaultMutableTreeNode node) {
        MPDDatabase db = mpd.getMPDDatabase();
        try {
            for (MPDArtist artist : db.listAllArtists()) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(artist);
                node.add(child);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        tree.expandPath(new TreePath(node.getPath()));
        tree.updateUI();
    }

    private void listAlbums(DefaultMutableTreeNode node, MPDArtist artist) {
        MPDDatabase db = mpd.getMPDDatabase();
        try {
            for (MPDAlbum album : db.listAlbumsByArtist(artist)) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(album);
                node.add(child);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    private void listSongs(DefaultMutableTreeNode node, MPDAlbum album) {
        MPDDatabase db = mpd.getMPDDatabase();
        try {
            for (MPDSong s : db.searchAlbum(album)) {
                if (album.getArtist().equals(s.getArtist())) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(s);
                    node.add(child);
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        treeScrollPanel = new javax.swing.JScrollPane();
        tree = new javax.swing.JTree();

        setLayout(new java.awt.GridBagLayout());

        treeScrollPanel.setMinimumSize(new java.awt.Dimension(260, 22));
        treeScrollPanel.setPreferredSize(new java.awt.Dimension(300, 275));

        tree.setRootVisible(false);
        tree.addTreeWillExpandListener(new javax.swing.event.TreeWillExpandListener() {
            public void treeWillCollapse(javax.swing.event.TreeExpansionEvent evt)throws javax.swing.tree.ExpandVetoException {
            }
            public void treeWillExpand(javax.swing.event.TreeExpansionEvent evt)throws javax.swing.tree.ExpandVetoException {
                treeTreeWillExpand(evt);
            }
        });
        tree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                treeMousePressed(evt);
            }
        });
        treeScrollPanel.setViewportView(tree);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 4, 2, 2);
        add(treeScrollPanel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void treeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeMousePressed
        TreePath[] paths = tree.getSelectionPaths();
        if (paths != null) {
            if (paths.length == 1 && evt.getClickCount() == 2) {
                TreePath path = paths[0];
                //System.out.println(path);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Object obj = node.getUserObject();
                if (obj instanceof MPDSong) {
                    MainForm.addSong((MPDSong) obj);
                }
            }
        }
    }//GEN-LAST:event_treeMousePressed

    private void treeTreeWillExpand(javax.swing.event.TreeExpansionEvent evt)throws javax.swing.tree.ExpandVetoException {//GEN-FIRST:event_treeTreeWillExpand
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();
        Object obj = node.getUserObject();
        if (obj instanceof MPDArtist) {
            listAlbums(node, (MPDArtist) obj);
        } else if (obj instanceof MPDAlbum) {
            listSongs(node, (MPDAlbum) obj);
        }
    }//GEN-LAST:event_treeTreeWillExpand


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTree tree;
    private javax.swing.JScrollPane treeScrollPanel;
    // End of variables declaration//GEN-END:variables

}
